package org.jeecg.chase.modules.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.chase.modules.entity.AdhShopCategory;
import org.jeecg.chase.modules.model.AdhShopCategoryTree;
import org.jeecg.chase.modules.service.IAdhShopCategoryService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author leikai
 * @version 1.0
 * @description: 商铺分类controller
 * @date 2022/01/08/0008 15:19
 */
@Slf4j
@RestController
@RequestMapping("/adh/shopCategory")
public class AdhShopCategoryController {

    @Autowired
    private IAdhShopCategoryService adhShopCategoryService;


    /**
     * 分页查询
     *
     * @param adhShopCategory
     * @param pageNo
     * @param pageSize
     * @param req
     * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage < org.jeecg.chase.modules.entity.AdhShopCategory>>
     * @author leikai
     * @date 2022/01/08/0008 15:49
     */
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @AutoLog(value = "分类分页查询", operateType = 1)
    public Result<IPage<AdhShopCategory>> queryPageList(AdhShopCategory adhShopCategory,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        HttpServletRequest req) {
        Result<IPage<AdhShopCategory>> result = new Result<IPage<AdhShopCategory>>();
        QueryWrapper<AdhShopCategory> queryWrapper = QueryGenerator.initQueryWrapper(adhShopCategory, req.getParameterMap());
        Page<AdhShopCategory> page = new Page<AdhShopCategory>(pageNo, pageSize);
        IPage<AdhShopCategory> pageList = adhShopCategoryService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 列表获取
     *
     * @param beginDate
     * @param endDate
     * @return org.jeecg.common.api.vo.Result<java.util.List < org.jeecg.chase.modules.model.AdhShopCategoryTree>>
     * @author leikai
     * @date 2022/01/08/0008 17:24
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @AutoLog(value = "分类列表查询", operateType = 1)
    public Result<List<AdhShopCategoryTree>> queryList(@RequestParam(name = "beginDate", required = false) String beginDate,
                                                       @RequestParam(name = "endDate", required = false) String endDate) {
        Result<List<AdhShopCategoryTree>> result = new Result<>();
        try {
            LambdaQueryWrapper<AdhShopCategory> query = new LambdaQueryWrapper<AdhShopCategory>();
            if (StringUtils.isNotBlank(beginDate)) {
                query.gt(AdhShopCategory::getCreateTime, DateUtils.str2Date(beginDate, DateUtils.yyyyMMdd.get()));
            }
            if (StringUtils.isNotBlank(endDate)) {
                query.lt(AdhShopCategory::getCreateTime, DateUtils.str2Date(endDate, DateUtils.yyyyMMdd.get()));
            }
            query.orderByAsc(AdhShopCategory::getCategoryOrder);
            List<AdhShopCategory> list = this.adhShopCategoryService.list(query);
            List<AdhShopCategoryTree> treeList = new ArrayList<>();
            getTreeList(treeList, list, null);
            result.setResult(treeList);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 新增
     *
     * @param adhShopCategory
     * @return org.jeecg.common.api.vo.Result<org.jeecg.chase.modules.entity.AdhShopCategory>
     * @author leikai
     * @date 2022/01/08/0008 15:54
     */
    @PostMapping("/add")
    @AutoLog(value = "分类新增", operateType = 2)
    public Result<AdhShopCategory> add(@RequestBody AdhShopCategory adhShopCategory) {
        Result<AdhShopCategory> result = new Result<AdhShopCategory>();
        try {
            adhShopCategory.setCreateTime(new Date());
            this.adhShopCategoryService.save(adhShopCategory);
            result.success("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 修改
     *
     * @param adhShopCategory
     * @return org.jeecg.common.api.vo.Result<org.jeecg.chase.modules.entity.AdhShopCategory>
     * @author leikai
     * @date 2022/01/08/0008 15:58
     */
    @PostMapping("/edit")
    @AutoLog(value = "分类修改", operateType = 3)
    public Result<AdhShopCategory> edit(@RequestBody AdhShopCategory adhShopCategory) {
        Result<AdhShopCategory> result = new Result<AdhShopCategory>();
        AdhShopCategory adhShopCategoryOld = this.adhShopCategoryService.getById(adhShopCategory.getId());
        if (adhShopCategoryOld == null) {
            result.error500("未找到对应实体");
        } else {
            adhShopCategory.setUpdateTime(new Date());
            boolean ok = this.adhShopCategoryService.updateById(adhShopCategory);
            if (ok) {
                result.success("修改成功");
            }
        }
        return result;
    }

    /**
     * 删除
     *
     * @param id
     * @return org.jeecg.common.api.vo.Result<?>
     * @author leikai
     * @date 2022/01/10/0010 15:46
     */
    @GetMapping("/delete")
    @AutoLog(value = "分类删除", operateType = 4)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            this.adhShopCategoryService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败");
        }
        return Result.OK("删除成功");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.system.entity.SysPermission>
     * @author leikai
     * @date 2022/01/10/0010 15:46
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.GET)
    @AutoLog(value = "分类批量删除", operateType = 4)
    public Result<SysPermission> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<SysPermission> result = new Result<>();
        try {
            String[] arr = ids.split(",");
            for (String id : arr) {
                if (oConvertUtils.isNotEmpty(id)) {
                    adhShopCategoryService.deleteById(id);
                }
            }
            result.success("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除成功!");
        }
        return result;
    }

    /**
     * 修改启用状态
     *
     * @param param
     * @return org.jeecg.common.api.vo.Result<?>
     * @author leikai
     * @date 2022/01/08/0008 16:14
     */
    @PostMapping("/updateStatus")
    @AutoLog(value = "分类启动状态修改", operateType = 3)
    public Result<?> updateStatus(@RequestBody Map<String, String> param) {
        String id = param.get("id");
        String status = param.get("status");
        if (StringUtils.isBlank(id) || StringUtils.isBlank(status)) {
            return Result.error("参数错误");
        }
        if (status.equals("1")) {
            boolean ok = this.adhShopCategoryService.updateStatus(id, 1);
            if (ok) {
                return Result.OK("启用成功");
            }
        } else {
            boolean ok = this.adhShopCategoryService.updateStatus(id, 0);
            if (ok) {
                return Result.OK("停用成功");
            }
        }
        return Result.OK("操作失败");
    }

    /**
     * 转化为tree
     *
     * @param treeList
     * @param metaList
     * @param temp
     * @return void
     * @author leikai
     * @date 2022/01/10/0010 15:47
     */
    private void getTreeList(List<AdhShopCategoryTree> treeList, List<AdhShopCategory> metaList, AdhShopCategoryTree temp) {
        for (AdhShopCategory adhShopCategory : metaList) {
            String tempPid = adhShopCategory.getParentId();
            AdhShopCategoryTree tree = new AdhShopCategoryTree(adhShopCategory);
            if (temp == null && oConvertUtils.isEmpty(tempPid)) {
                treeList.add(tree);
                if (tree.getCategoryLevel() != 2) {
                    getTreeList(treeList, metaList, tree);
                }
            } else if (temp != null && tempPid != null && tempPid.equals(temp.getId())) {
                temp.getChildren().add(tree);
                if (tree.getCategoryLevel() != 2) {
                    getTreeList(treeList, metaList, tree);
                }
            }

        }
    }

    /**
     * 一级分类列表查询
     *
     * @return org.jeecg.common.api.vo.Result<java.util.List < java.util.Map < java.lang.String, java.lang.Object>>>
     * @author leikai
     * @date 2022/01/10/0010 15:55
     */
    @GetMapping("/queryParentData")
    @AutoLog(value = "一级分类列表查询", operateType = 1)
    public Result<List<Map<String, Object>>> queryParentData() {
        Result<List<Map<String, Object>>> result = new Result<>();
        try {
            List<Map<String, Object>> mapList = this.adhShopCategoryService.queryParentData();
            for (Map<String, Object> cate : mapList) {
                String cateId = (String)cate.get("value");
                List<Map<String, Object>> list1 = adhShopCategoryService.querySubCategoryData(cateId);
                cate.put("children",list1);
            }
            result.setResult(mapList);
            result.success("查询成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("查询失败");
        }
        return result;
    }
}
